import { RootState } from '@/types/store'
import { Input, NavBar, TextArea } from 'antd-mobile'
import { InputRef } from 'antd-mobile/es/components/input'
import { TextAreaRef } from 'antd-mobile/es/components/text-area'
import { useEffect, useRef, useState } from 'react'
import { useSelector } from 'react-redux'

import styles from './index.module.scss'
// 父传子数据类型
type Props = {
  hideInput: () => void
  type: '' | 'name' | 'intro'
  onUpdate: (key: string, value: string) => void
}

// 解构出数据

const EditInput = ({ hideInput, type, onUpdate }: Props) => {
  // 数据回显  从仓库中那数据
  const { userProfile } = useSelector((state: RootState) => state.profile)
  // console.log(userProfile)
  // 自动获取光标
  const inputRef = useRef<InputRef>(null)
  const textRef = useRef<TextAreaRef>(null)
  useEffect(() => {
    if (type === 'name') {
      inputRef.current?.focus()
    } else {
      textRef.current?.focus()
      // textarea控制光标 在最后面   1，-1 全选
      document.querySelector('textarea')?.setSelectionRange(-1, -1)
    }
  })
  // 初始值
  const [value, setValue] = useState(
    type === 'name' ? userProfile.name : userProfile.intro
  )

  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        onBack={hideInput}
        right={
          <span
            className="commit-btn"
            onClick={() => {
              onUpdate(type, value)
            }}
          >
            提交
          </span>
        }
      >
        编辑{type === 'name' ? '昵称' : '简介'}
      </NavBar>

      <div className="edit-input-content">
        <h3>编辑{type === 'name' ? '昵称' : '简介'}</h3>
        {type === 'name' ? (
          <div className="input-wrap">
            <Input
              placeholder="请输入"
              value={value}
              onChange={(e) => setValue(e)}
              maxLength={12}
              ref={inputRef}
            />
          </div>
        ) : (
          <TextArea
            className="textarea"
            placeholder="请输入简介"
            showCount
            maxLength={99}
            value={value}
            ref={textRef}
            onChange={(e) => setValue(e)}
          ></TextArea>
        )}
      </div>
    </div>
  )
}

export default EditInput
